﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using OreSystem.Common;
using System.Configuration;
using NHibernate.Cfg;
using System.Xml;
using System.Xml.Linq;
namespace OreSystem.SystemInit
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }
        public void CreateFile(string filePath)
        {

        }
        public void CreateDir(string path)
        {
            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show("创建数据库失败" + ex.ToString());
            }
            
        }
        

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = @"D:\DataBase";
            ofd.Filter = "*.mdf|*.mdf";
            if (ofd.ShowDialog()== System.Windows.Forms.DialogResult.OK)
            {
                textBox1.Text = ofd.FileName;
                textBox2.Text = textBox1.Text.Substring(0, textBox1.Text.IndexOf(".")) + ".ldf";
            }
        }
        //附加数据库
        private void button3_Click(object sender, EventArgs e)
        {
            string dbFile = textBox1.Text;
            string dbLogFile = textBox2.Text;
            string addSql = string.Format(@"
use master
if Exists(select * from dbo.sysdatabases where name='OreSystemData')
begin
--drop database 'OreSystemData'
EXEC sp_detach_db 'OreSystemData', 'true';
end
else
begin
EXEC sp_attach_db @dbname = 'OreSystemData', 
@filename1 = '{0}', 
@filename2 = '{1}'
end", dbFile, dbLogFile);
            try
            {
                MsSqlHelper.ExceuteNoQuery(addSql, null);
                MessageBox.Show("附加成功");
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        //分离数据库
        private void button4_Click(object sender, EventArgs e)
        {
            string sql = @"if Exists(select * from dbo.sysdatabases where name='OreSystemData')
begin
--drop database 'OreSystemData'
EXEC sp_detach_db 'OreSystemData', 'true';
end";
            int isExists = (int)MsSqlHelper.ExecuteScalar("select count(*) from dbo.sysdatabases where name='OreSystemData'",null);
            if (isExists < 1)
            {
                MessageBox.Show("数据库不存在");
                return;
            }
            MsSqlHelper.ExceuteNoQuery(sql);
        }

        private void button7_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox3.Text = fbd.SelectedPath;
                textBox4.Text = DateTime.Now.ToString("yyyyMMddHHmmss")+"_"+DateTime.Now.Millisecond.ToString()+".bak";
                
            }
        }
        //备份数据库
        private void button6_Click(object sender, EventArgs e)
        {
            string bakFile = Path.Combine(textBox3.Text, textBox4.Text);
//            string sqlBackDatabase = string.Format(@"BACKUP DATABASE OreSystemData
//  TO DISK = '{0}' 
//  WITH init;", bakFile);
            string DataBaseName = comboBox4.SelectedValue.ToString();
            try
            {
                ToolSql.BackDataBase(DataBaseName, bakFile);
                MessageBox.Show("备份成功");
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.ToString());
            }
        }
       
        //测试数据连接
        private void btnTestConnectionSql_Click(object sender, EventArgs e)
        {
            if (ToolSql.ExistSqlServerService())
            {
                //MessageBox.Show("数据库已安装");
            }
            else
            {
                MessageBox.Show("没有安装数据库,请先安装数据库");
                return;
            }
            try
            {
               string resultMsg = MsSqlHelper.openConnection(comboBox1.SelectedValue.ToString(), txtSqlUserName.Text, txtSqlPw.Text);
               MessageBox.Show("连接成功！");
            }
            catch (Exception ex)
            {

                MessageBox.Show("连接失败");
            }
            
        }
        //重置管理员密码
        private void button5_Click(object sender, EventArgs e)
        {
            string sql = @"use OreSystemData
if Exists( select * from T_User where UserName = 'admin')
begin
update T_User set PassWord='A47A40EFFCC8A631459D04E205888502' where UserName = 'admin'
end
else
begin
insert into T_User  values('admin','A47A40EFFCC8A631459D04E205888502',0,getDate());
end";
            try
            {
                MsSqlHelper.ExceuteNoQuery(sql);
                MessageBox.Show("重置密码成功密码为：admin");
            }
            catch (Exception ex)
            {
                
                throw ex;
            }
        }

        

        private void button9_Click(object sender, EventArgs e)
        {
            string constr = string.Format("Data Source={0}; Initial Catalog=master;User ID={1};Password={2}", comboBox1.SelectedValue.ToString(), txtSqlUserName.Text, txtSqlPw.Text);
            AppConfigTool.UpdateConnectionStringsConfig("mssql", constr, "");
            try
            {
                string resultMsg = MsSqlHelper.openConnection(comboBox1.SelectedValue.ToString(), txtSqlUserName.Text, txtSqlPw.Text);
                MessageBox.Show("连接成功！");
            }
            catch (Exception ex)
            {

                MessageBox.Show("连接失败");
            }
           
        }

       

       
        //启用sa，并修改sa的密码
        private void btnEnableSa_Click(object sender, EventArgs e)
        {
            //使用windows登陆模式连接
            string connstr = string.Format(@"Server={0};Database=master;Trusted_Connection=True;", comboBox2.SelectedValue);
            string sql = string.Format(@"ALTER LOGIN sa ENABLE;
ALTER LOGIN sa WITH PASSWORD = '{0}';",txtSaPwd.Text);
            try
            {
                MsSqlHelper.ExceuteNoQueryByConnStr(sql, connstr, null);
                string connStr = string.Format("server={0};database=OreSystemData;uid=sa;pwd={1};", comboBox2.SelectedValue, txtSaPwd.Text);
                string configPath = @"Config/Hib.cfg.xml";
                string xmlFile = Path.Combine(Application.StartupPath, configPath);
                SetNHConfig(connStr, xmlFile);
                MessageBox.Show("设置成功");
            }
            catch (Exception ex)
            {

                MessageBox.Show("失败"+ex.ToString());
            }
        }
        
        private void button11_Click(object sender, EventArgs e)
        {
            try
            {
               string resultMessage =  MsSqlHelper.OpenConnection(txtConnStr.Text);
               MessageBox.Show(resultMessage);
                
            }
            catch (Exception ex)
            {
                
                throw ex;
            }
            
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            List<object> dataSource = new List<object>();
            dataSource.Add(new { Text = "MSSQLSERVER", Value = "." });
            dataSource.Add(new { Text = "SQLEXPRESS", Value = @".\sqlexpress" });
            comboBox2.DataSource = dataSource;
            comboBox2.ValueMember = "Value";
            comboBox2.DisplayMember = "Text";
            comboBox1.DataSource = dataSource;
            comboBox1.ValueMember = "Value";
            comboBox1.DisplayMember = "Text";
            initDataBase();
            initCmb4();
        }
        public void initDataBase()
        {
            DataTable dt = MsSqlHelper.ExcuteQuery("select * from master.dbo.sysdatabases order by dbid desc", null);
            comboBox3.DataSource = dt;
            comboBox3.DisplayMember = "name";
            comboBox3.ValueMember = "name";
        }

        public void initCmb4()
        {
            DataTable dt = MsSqlHelper.ExcuteQuery("select * from master.dbo.sysdatabases order by dbid desc", null);
            comboBox4.DataSource = dt;
            comboBox4.DisplayMember = "name";
            comboBox4.ValueMember = "name";
        }
        //修改nh 的配置文件的sql 连接
        private void button12_Click(object sender, EventArgs e)
        {

            string connStr = string.Format("server={0};database=OreSystemData;uid=sa;pwd={1};", comboBox2.SelectedValue, txtSaPwd.Text);
            string configPath = @"Config/Hib.cfg.xml";
            string xmlFile = Path.Combine(Application.StartupPath, configPath);
            SetNHConfig(connStr, xmlFile);
        }
        public void SetNHConfig(string connStr,string configFilePath)
        {
            
            XmlDocument xmldoc = new XmlDocument();
            XmlNamespaceManager manager = new XmlNamespaceManager(xmldoc.NameTable);
            manager.AddNamespace("ab", "urn:nhibernate-configuration-2.2");
            xmldoc.Load(configFilePath);
            XmlNode node = xmldoc.SelectNodes("/ab:hibernate-configuration/ab:session-factory/ab:property[@name='connection.connection_string']", manager)[0];
            node.InnerText = connStr;
            xmldoc.Save(configFilePath);
        }
        //创建新的数据库
        private void button14_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txt_DataBaseName.Text))
            {
                MessageBox.Show("数据库名不能为空");
                return;
            }
            if (!Directory.Exists(txt_DataBaseFilePath.Text))
            {
                MessageBox.Show("文件存放位置不存在");
                return;
            }
            string initDir = txt_DataBaseFilePath.Text;
            string dataBaseName = txt_DataBaseName.Text;
            string initDataBack = Path.Combine(initDir, "BackData");
            CreateDir(initDir);
            CreateDir(initDataBack);
            string fileMdf = Path.Combine(initDir, dataBaseName+".mdf");
            string fileldf = Path.Combine(initDir, dataBaseName+".ldf");
            string DataBaseIsExistSql = string.Format("select count(*) isExist from master.dbo.sysdatabases where [name] = '{0}'", dataBaseName);
            object isExist = MsSqlHelper.ExecuteScalar(DataBaseIsExistSql, null);
            if (Convert.ToBoolean(isExist))
            {
                if (MessageBox.Show("数据库已经存在是否删除？", "提示信息", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    MsSqlHelper.ExceuteNoQuery(string.Format("drop database {0}", dataBaseName));
                    MessageBox.Show("删除成功！");
                }
                else
                {
                    MessageBox.Show("请选择其他名字");
                    return;
                };
            }
            if (File.Exists(fileMdf))
            {
                if (MessageBox.Show("数据库文件已经存在是否删除？", "提示信息", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    File.Delete(fileMdf);
                    File.Delete(fileldf);
                    MessageBox.Show("删除成功！");
                }
                else
                {
                    MessageBox.Show("请把文件复制到其他地方");
                    return;
                };
            }
            
            string CreateDataBaseSql = string.Format(@"USE [master]
CREATE DATABASE [{2}] ON  PRIMARY 
( NAME = N'LC_GGMES', FILENAME = N'{0}' , SIZE = 16384KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'LC_GGMES_log', FILENAME = N'{1}' , SIZE = 136064KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)", fileMdf, fileldf, dataBaseName);
            try
            {
                MsSqlHelper.ExceuteNoQuery(CreateDataBaseSql, null);
                MessageBox.Show("创建成功！");
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.ToString());

            }
        }

        private void button13_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txt_DataBaseFilePath.Text = fbd.SelectedPath;
            }
            
            
        }

        private void btn_ResortDataBase_Click(object sender, EventArgs e)
        {
            string restoreDataBase = @"USE MASTER
ALTER DATABASE {0} SET OFFLINE WITH ROLLBACK IMMEDIATE
RESTORE DATABASE {0}
FROM DISK='{1}'
WITH REPLACE";

            string DataBaseName = string.Empty;
            string BackFile = string.Empty;
            if (string.IsNullOrEmpty(txt_BackFile.Text))
            {
                MessageBox.Show("没有选择备份文件");
                return;
                
            }
            BackFile = txt_BackFile.Text;
            DataBaseName = comboBox3.SelectedValue.ToString();
            if (!File.Exists(BackFile))
            {
                MessageBox.Show("备份文件不存在");
                return;
            }
            string sql = string.Format(restoreDataBase,DataBaseName,DataBaseName);
            try
            {
                MsSqlHelper.ExceuteNoQuery(sql, null);
                MessageBox.Show("数据库还原成功");
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.ToString());
            }
                
        }

        private void comboBox3_Click(object sender, EventArgs e)
        {
            initDataBase();
        }

        private void btn_SelectBackFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txt_BackFile.Text = ofd.FileName;
            }
        }

       
       
    }
}
